<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class=" fr" @click="createItem" v-permission="'barcode.add'">创建条码规则
    </el-button>
    <div class="panel-body">
      <div class="filter-container">
        <el-input style="width: 200px" placeholder="输入编号/名称搜索" clearable prefix-icon="el-icon-search"
          class="filter-item" @keyup.enter.native="research" @clear="research" v-model="query.rule">
        </el-input>
        <!-- <el-input style="width: 190px" placeholder="输入要素代码搜索" clearable prefix-icon="el-icon-search"
                class="filter-item" @keyup.enter.native="research" @clear="research" v-model="query.factor"></el-input> -->
        <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
        <div class="flex1"></div>

      </div>
      <z-table :list="list" :tableProps="tableProps" :columns="columns" @row-click="mainRowClick" @editItem="editItem"
        @deleteItem="deleteItem">
        <template v-slot:operation="v">
          <!-- <a href="#" class="text-green" v-permission="subassemblyName +'.edit'"
            @click.prevent.stop="ruDetailShow(v.row)">规则明细</a> -->
          <a href="#" class="text-blue" v-permission="subassemblyName +'.edit'"
            @click.prevent.stop="editItem(v.row)">编辑</a>
          <a href="#" class="text-red" v-permission=" subassemblyName +'.delete'"
            @click.prevent.stop="deleteItem(v.row)">删除</a>
        </template>
      </z-table>
      <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
        @change="getList"></z-pagination>
    </div>
    <div class="panel-info mt-10" v-if="mainId">
      <div class="panel-title">规则适用物料</div>
      <div class="panel-body">
        <ma-barcode :row="row" />
      </div>
    </div>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>
    <z-form-dialog :name="name2" :data="data2" :formProps="formProps2" :fields="fields2" @submit="submit2"
      :submitLoading="submitLoading2" :visible.sync="editFormVisible2"></z-form-dialog>
    <el-dialog :title="'规则明细'" :width="formProps.dialogWidth" :close-on-click-modal="false"
      :visible.sync="editFormVisible3">
      <div>
        <el-button style="margin-bottom: 10px" type="primary" class="fl" size="mini" @click="createItem2">
          添加规则明细</el-button>
        <el-button v-if="sortFlag" :loading="sortLoading" style="margin-bottom: 10px" type="success" class="fl"
          size="mini" @click="saveSort">
          保存排序</el-button>
        <el-tag class="ml-10" v-else type="info">提示：拖动表格行可进行排序</el-tag>
        <z-table ref="dragTable" v-loading="detailPageLoading" :list="list2" :tableProps="tableProps2"
          :columns="columns2" @editItem="editItem2" @deleteItem="deleteItem2">
        </z-table>
        <div class="text-right" style="margin-top:30px">
          <el-button @click="editFormVisible3 = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import maBarcode from '@/views/masterdata/barcode/maBarcode'
import Sortable from 'sortablejs'
export default {
  mixins: [commonMixin],
  components: { maBarcode },
  name: 'barcode',
  data: function () {
    return {
      editFormVisible3: false,
      row: {},
      subassemblyName: '',
      api: this.$api.barcodeRule,
      apiCreate: this.$api.barcodeRule + 'modify',
      apiEdit: this.$api.barcodeRule + 'modify',
      name: '条码规则',
      initData: { is_common: '0', type: '', level: '' },
      tableProps: {
        border: true,
        opsColWith: 160,
        fixed: false,
        highlightCurrentRow: true,
        hideOperations: false,
      },
      pagination: {
        //分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, jumper, ->, total, sizes',
      },
      dicObj: {},
      columns: [
        { title: '是否通用', key: 'is_common_name', width: 90 },
        { title: '规则编号', key: 'barcode_rule_no', width: 120 },
        { title: '规则名称', key: 'rule_name', width: 140 },
        { title: '规则类型', key: 'type_name', width: 80 },
        { title: '条码层级', key: 'level', width: 90 },
        { title: '规则描述', key: 'rule_description' },
        { title: '区段分隔符', key: 'split_char', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      fields: [
        {
          title: '是否通用',
          name: 'select',
          key: 'is_common',
          span: 12,
          required: true,
          options: [
            { value: '0', label: '非通用' },
            { value: '1', label: '通用' },
          ],
          events: { change: null },
        },
        { title: '规则编号', key: 'barcode_rule_no', span: 12, required: true },
        { title: '规则名称', key: 'rule_name', span: 12, required: true },
        {
          title: '条码类型',
          required: true,
          key: 'type',
          span: 12,
          name: 'select',
          options: [],
          events: { change: null },
        },
        { title: '条码层级', required: true, key: 'level', span: 12, name: 'select', options: [] },
        { title: '规则描述', key: 'rule_description', span: 12 },
        { title: '区段分隔符', key: 'split_char', span: 12 },
      ],
      codingTypes: [
        { label: 'Datetime 日期时间', value: 'Datetime' },
        { label: 'String 固定字串', value: 'String' },
        { label: 'SerialNumber 流水号', value: 'SerialNumber' },
        { label: 'View 视图', value: 'View' },
        { label: 'Param 参数', value: 'Param' },
      ],
      factorOptions: [],
      mainId: '',
      name2: '条码规则明细',
      sortFlag: false,
      sortLoading: false,
      detailPageLoading: false,
      columns2: [
        { title: '区段序号', key: 'sequence', width: 72 },
        { title: '区段类型', key: 'coding_type', width: 100 },
        { title: '要素代码', key: 'coding_param', width: 100 },
        { title: '要素名称', key: 'coding_desc' },
        { title: '值', key: 'field_value', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      fields2: [
        {
          title: '区段序号',
          key: 'sequence',
          name: 'text',
          props: { disbaled: true },
          tips: '序号越小区段越靠前',
        },
        {
          title: '区段类型',
          key: 'factor_type',
          required: true,
          name: 'select',
          options: [],
          props: {},
          events: { change: null },
        },
        {
          title: '要素',
          key: 'factor_id',
          required: true,
          name: 'select',
          options: [],
          props: {},
          events: { change: null },
        },
        {
          title: '要素值',
          props: { disbaled: false },
          key: 'field_value',
          name: 'text',
          options: [],
          tips: '区段类型为View时，选择字段名，区段值类型为Param时，填写参数名',
        },
        {
          title: '流水号重置',
          key: 'reset_flag',
          span: 12,
          required: true,
          name: 'switch',
          tips: '选中表示此区段值的变化，将引起流水号的重置',
          props: { disabled: false, activeValue: 'Y', inactiveValue: 'N' },
        },
        {
          title: '流水号起始值',
          key: 'reset_start_value',
          span: 12,
          name: 'number',
          props: { min: 0, disbaled: false },
          tips: '填写10进制整数值',
        },
        { title: '备注', key: 'remarks', name: 'textarea' },
      ],
      tableProps2: {
        border: true,
        opsColWith: 80,
        fixed: false,
        'row-key': 'id',
        highlightCurrentRow: false,
        hideOperations: false,
      },
      formProps2: {
        dialogWidth: '70%',
        labelWidth: '140px',
      },
      list2: [],
      data2: {},
      sortList: [],
      submitLoading2: false,
      editFormVisible2: false,
      query: {
        queryString: {
          rule: '',
          factor: '',
        },
        size: 10,
        page: 1,
      },
      customerOptions: [],
      groupOptions: [],
      mappingLevel: {},
      detailDialogMainId: null,
    }
  },
  methods: {
    ruDetailShow(v) {
      this.sortFlag = false
      this.editFormVisible3 = true
      this.detailDialogMainId = v.id
      this.getList2()
    },
    research() {
      this.query.page = 1
      this.list = []
      this.total = 0
      this.mainId = ''
      this.getList()
    },
    getPackageLevel() {
      this.$request(this.$api.dictionary + 'getdirectchildren', {
        parentType: 'package_level_name',
      }).then((r) => {
        r.forEach((v) => {
          this.mappingLevel[v.value] = v.label
        })

        this.getFieldConfig1('level').options = this.arrayOptions(r, 'value', ['label'])
      })
    },
    getFieldConfig1(fieldName) {
      var j = _.findIndex(this.fields, (i) => i.key == fieldName)
      if (j != -1) {
        return this.fields[j]
      }
      return null
    },
    isCommonChange(v) {
      if (this.data.is_common == 1) {
        this.data.type = ''
        this.getFieldConfig1('type').hidden = true
        this.getFieldConfig1('level').hidden = true
        this.data.level = ''
      } else {
        this.getFieldConfig1('type').hidden = false
        if (this.data.type == 3) this.getFieldConfig1('level').hidden = false
      }
    },
    barcodeTypeChange(v) {
      if (this.data.type != 3) {
        this.data.level = ''
        this.getFieldConfig1('level').hidden = true
      } else {
        this.getFieldConfig1('level').hidden = false
      }
    },
    mainRowClick(row) {
      // this.row = row
      // this.mainId = row.id
    },
    formatList(list) {
      //依据实际需求处理
      list.forEach((v) => {
        v.level = this.mappingLevel[v.level]
        v.type_name = this.dicObj[v.type]
        v.is_common_name = v.is_common == 1 ? '是' : '否'
      })
      return list
    },
    formatAfterGet(v) {
      v.is_common = v.is_common.toString()
      v.type = v.type ? v.type.toString() : ''
      if (v.type == 3) {
        this.getFieldConfig1('level').hidden = false
      } else {
        this.getFieldConfig1('level').hidden = true
      }
      return v
    },
    createItem() {
      this.$router.push({ name: 'barcodeInfo', query: { isEidt: false } })
      // this.data = _.cloneDeep(this.initData)
      // this.editFormVisible = true
      // this.getFieldConfig1('level').hidden = true
    },
    submit() {
      let insertUrl = this.apiCreate
      let updateUrl = this.apiEdit
      let url = this.data.id ? updateUrl : insertUrl
      let data = this.formatBeforeSave(this.data)
      let check = this.validataData(this.fields, data)
      if (!check) return
      this.submitLoading = true
      this.$request(url, data, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.mainId = ''
          this.editFormVisible = false
          this.getList()
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    paginationschane(val) {
      this.getList2()
    },
    getList2() {
      this.detailPageLoading = true
      this.$request(this.$api.barcodeRule + 'detailgetlist', {
        rule_id: this.detailDialogMainId,
        size: 999,
        page: 1,
      })
        .then((r) => {
          this.detailPageLoading = false
          this.list2 = r.list
          this.sortList = r.list.map((v) => {
            return v.id
          })
          this.initSortable()
        })
        .catch((e) => {
          this.detailPageLoading = false
        })
    },
    createItem2() {
      let q = this.list2.length || 0
      this.data2 = { barcode_rule_id: this.detailDialogMainId, sequence: q + 1 }
      this.editFormVisible2 = true
    },
    editItem(row) {
      this.$router.push({ name: 'barcodeInfo', query: { isEidt: true, id: row.id } })
    },
    editItem2(row) {
      this.pageLoading = true
      this.$request(this.$api.barcodeRule + 'detailgetbyid', {
        id: row.id,
      })
        .then((r) => {
          this.pageLoading = false
          let data = r
          data.factor_type = row.coding_type
          this.data2 = data
          this.typeChange(data.factor_type)
          this.factorChange(data.factor_id)
          this.editFormVisible2 = true
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    submit2() {
      this.submitLoading2 = true
      this.$request(this.$api.barcodeRule + 'detailmodify', this.data2, 'post')
        .then((r) => {
          this.submitLoading2 = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editFormVisible2 = false
          this.getList2()
        })
        .catch(() => {
          this.submitLoading2 = false
        })
    },
    deleteItem2(v) {
      this.$confirm('确定要删除这条记录？', '操作确认').then(() => {
        this.pageLoading = true
        let url = this.$api.barcodeRule + 'detaildelete'
        this.$request(url + '/' + v.id, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.getList2()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    saveSort() {
      if (this.sortList.length == 0) return this.$message.error('没有需要保存的数据')
      this.sortLoading = true
      this.$request(this.$api.barcodeRule + 'detailSaveSort', this.sortList, 'post').then((r) => {
        this.sortLoading = false
        this.$message.success('保存排序成功。')
        this.getList2()
      })
    },
    getMatOptions(query) {
      if (query) {
        this.$request(this.$api.mat + 'getmatandsku', { queryString: query })
          .then((r) => {
            this.setFieldOptions('sku_id', r, 'id', ['key_part_no', 'key_part_name', 'key_part_desc'])
          })
          .catch(() => {})
      } else {
        this.setFieldOptions('sku_id', [])
      }
    },
    singleMatOptions(id) {
      if (id) {
        this.$request(this.$api.mat + 'getmatandsku', { id: id })
          .then((r) => {
            this.setFieldOptions('sku_id', r, 'id', ['key_part_no', 'key_part_name', 'key_part_desc'])
          })
          .catch(() => {})
      } else {
        this.setFieldOptions('sku_id', [])
      }
    },
    getFieldConfig(fieldName) {
      var j = _.findIndex(this.fields3, (i) => i.key == fieldName)
      if (j != -1) {
        return this.fields3[j]
      }
      return null
    },

    typeChange(v) {
      this.fields2.find((i) => i.key == 'field_value').props.disabled = true
      this.fields2.find((i) => i.key == 'reset_start_value').props.disabled = true
      this.fields2.find((i) => i.key == 'reset_flag').props.disabled = true
      if (v == 'SerialNumber') this.fields2.find((i) => i.key == 'reset_start_value').props.disabled = false
      if (v == 'View' || v == 'Param') this.fields2.find((i) => i.key == 'field_value').props.disabled = false
      if (v != 'SerialNumber') this.fields2.find((i) => i.key == 'reset_flag').props.disabled = false
      var tmp = this.fields2.find((i) => i.key == 'factor_id')
      tmp.options = this.factorOptions.filter((i) => i.type == v)
    },
    factorChange(v) {
      var f = this.factorOptions.find((i) => i.value == v)
      if (this.data2.factor_type == 'View') {
        this.$request(this.$api.param + 'getbyname', { type: 'LABEL_VIEW_FIELDS', name: f.coding_param }).then((r) => {
          var tmp = this.fields2.find((i) => i.key == 'field_value')
          tmp.name = 'select'
          tmp.options = r.map((i) => ({
            label: `${i.param_value} ${i.param_condition1}`,
            value: i.param_value,
          }))
        })
      } else {
        var tmp = this.fields2.find((i) => i.key == 'field_value')
        tmp.name = 'text'
        tmp.options = []
      }
    },

    initSortable() {
      // 获取表格row的父节点
      const ele = this.$refs.dragTable.$el.querySelector('.el-table__body > tbody')
      // 创建拖拽实例
      let dragTable = Sortable.create(ele, {
        animation: 150, //动画
        disabled: false, // 拖拽不可用? false 启用（刚刚渲染表格的时候起作用，后面不起作用）
        // 开始拖动事件
        onStart: () => {},
        // 结束拖动事件
        onEnd: ({ newIndex, oldIndex }) => {
          this.sortFlag = true
          let tmp = this.sortList[newIndex]
          this.sortList[newIndex] = this.sortList[oldIndex]
          this.sortList[oldIndex] = tmp
        },
      })
    },
  },
  created: function () {
    this.fields2.find((i) => i.key == 'sequence').props.disabled = true
    this.subassemblyName = this.$route.name
    this.getPackageLevel()
    this.getFieldConfig1('type').events.change = this.barcodeTypeChange
    this.getFieldConfig1('is_common').events.change = this.isCommonChange

    this.$request(this.$api.dictionary + 'getdirectchildren', {
      parentType: 'barcode_label_type',
    }).then((r) => {
      this.getFieldConfig1('type').options = this.arrayOptions(r, 'value', ['label'])
      r.forEach((v) => {
        this.dicObj[v.value] = v.label
      })
    })
    this.getList()
    var tmp = this.fields2.find((i) => i.key == 'factor_type')
    tmp.options = this.codingTypes
    tmp.events.change = this.typeChange

    tmp = this.fields2.find((i) => i.key == 'factor_id')
    tmp.events.change = this.factorChange

    this.$request(this.$api.factor + 'getlist', { page: 1, size: 99 }).then((r) => {
      this.factorOptions = r.list.map((i) => {
        return {
          label: `${i.coding_param} ${i.coding_desc}  ${i.sample_value ? '示例：' + i.sample_value : ''}`,
          value: i.id,
          type: i.coding_type,
          coding_param: i.coding_param,
        }
      })
    })
  },
}
</script>
<style scoped>
::v-deep .el-card__header {
  padding: 8px 20px !important;
}
</style>
